package com.seu.vcampus.view;

import com.seu.vcampus.client.VCampusClient;
import com.seu.vcampus.util.UIStyleUtil;
import com.seu.vcampus.vo.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * 现代化主界面 - 采用按钮导航设计
 * 通过按钮打开独立的功能窗口，而不是在同一界面中显示
 * 
 * @author 虚拟校园开发团队
 * @since 2.1.0
 */
public class ModernMainFrame extends JFrame {
    private VCampusClient client;
    private User currentUser;
    private JLabel welcomeLabel;
    private JPanel buttonPanel;
    private Map<String, JFrame> openWindows;
    
    public ModernMainFrame(VCampusClient client, User user) {
        super("虚拟校园系统 - 主界面");
        this.client = client;
        this.currentUser = user;
        this.openWindows = new HashMap<>();
        
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);
        setResizable(false);
    }
    
    /**
     * 初始化组件
     */
    private void initializeComponents() {
        // 欢迎标签
        welcomeLabel = new JLabel("欢迎, " + currentUser.getUsername() + 
                                 " (" + com.seu.vcampus.util.UserTypeUtil.getUserTypeText(currentUser.getUserType()) + ")");
        welcomeLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        welcomeLabel.setForeground(new Color(66, 133, 244));
        
        // 按钮面板
        buttonPanel = new JPanel(new GridBagLayout());
        buttonPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        buttonPanel.setBackground(new Color(248, 249, 250));
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(Color.WHITE);
        
        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(222, 226, 230)),
            new EmptyBorder(20, 30, 20, 30)
        ));
        topPanel.setBackground(Color.WHITE);
        
        // 欢迎信息
        JPanel welcomePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        welcomePanel.setOpaque(false);
        welcomePanel.add(welcomeLabel);
        topPanel.add(welcomePanel, BorderLayout.WEST);
        
        // 退出按钮
        JButton logoutButton = UIStyleUtil.createSecondaryButton("退出登录");
        logoutButton.addActionListener(e -> logout());
        
        JPanel buttonPanelEast = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanelEast.setOpaque(false);
        buttonPanelEast.add(logoutButton);
        topPanel.add(buttonPanelEast, BorderLayout.EAST);
        
        // 创建功能按钮
        createFunctionButtons();
        
        // 滚动面板
        JScrollPane scrollPane = new JScrollPane(buttonPanel);
        scrollPane.setBorder(null);
        scrollPane.getViewport().setBackground(new Color(248, 249, 250));
        
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        
        add(mainPanel);
    }
    
    /**
     * 创建功能按钮
     */
    private void createFunctionButtons() {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        
        int row = 0;
        int col = 0;
        
        // 根据用户类型创建按钮
        String userTypeStr = currentUser.getUserType() != null ? 
                           currentUser.getUserType().name() : "";
        
        if ("STUDENT".equals(userTypeStr)) {
            addButton(buttonPanel, "个人信息", "user_info", row, col++, gbc);
            addButton(buttonPanel, "学籍管理", "student_mgmt", row, col++, gbc);
            addButton(buttonPanel, "选课系统", "course_select", row, col++, gbc);
            addButton(buttonPanel, "图书馆", "library", ++row, 0, gbc);
            addButton(buttonPanel, "校园商店", "store", row, 1, gbc);
            addButton(buttonPanel, "成绩查询", "grades", row, 2, gbc);
        } else if ("TEACHER".equals(userTypeStr)) {
            addButton(buttonPanel, "个人信息", "user_info", row, col++, gbc);
            addButton(buttonPanel, "课程管理", "course_mgmt", row, col++, gbc);
            addButton(buttonPanel, "学生管理", "student_mgmt", row, col++, gbc);
            addButton(buttonPanel, "成绩录入", "grade_entry", ++row, 0, gbc);
            addButton(buttonPanel, "教学评估", "evaluation", row, 1, gbc);
        } else if ("ADMIN".equals(userTypeStr) || "SYSTEM_ADMIN".equals(userTypeStr)) {
            addButton(buttonPanel, "个人信息", "user_info", row, col++, gbc);
            addButton(buttonPanel, "用户管理", "user_mgmt", row, col++, gbc);
            addButton(buttonPanel, "图书馆管理", "library_mgmt", row, col++, gbc);
            addButton(buttonPanel, "系统管理", "system_mgmt", ++row, 0, gbc);
            addButton(buttonPanel, "数据统计", "statistics", row, 1, gbc);
            addButton(buttonPanel, "系统监控", "monitoring", row, 2, gbc);
        } else if ("LIBRARY_ADMIN".equals(userTypeStr)) {
            addButton(buttonPanel, "个人信息", "user_info", row, col++, gbc);
            addButton(buttonPanel, "图书馆管理", "library_mgmt", row, col++, gbc);
            addButton(buttonPanel, "借阅管理", "borrow_mgmt", row, col++, gbc);
            addButton(buttonPanel, "图书编目", "cataloging", ++row, 0, gbc);
        } else if ("FINANCE_ADMIN".equals(userTypeStr)) {
            addButton(buttonPanel, "个人信息", "user_info", row, col++, gbc);
            addButton(buttonPanel, "财务管理", "finance_mgmt", row, col++, gbc);
            addButton(buttonPanel, "收支统计", "income_stats", row, col++, gbc);
            addButton(buttonPanel, "费用设置", "fee_settings", ++row, 0, gbc);
        } else {
            addButton(buttonPanel, "个人信息", "user_info", row, col++, gbc);
            addButton(buttonPanel, "图书馆", "library", row, col++, gbc);
        }
    }
    
    /**
     * 添加功能按钮
     */
    private void addButton(JPanel panel, String text, String actionCommand, 
                          int row, int col, GridBagConstraints gbc) {
        gbc.gridx = col;
        gbc.gridy = row;
        
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(200, 120));
        
        // 设置按钮样式
        button.setBackground(Color.WHITE);
        button.setForeground(new Color(66, 133, 244));
        button.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(66, 133, 244), 2),
            new EmptyBorder(10, 10, 10, 10)
        ));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // 悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(66, 133, 244));
                button.setForeground(Color.WHITE);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(Color.WHITE);
                button.setForeground(new Color(66, 133, 244));
            }
        });
        
        button.setActionCommand(actionCommand);
        button.addActionListener(this::handleFunctionButtonClick);
        
        panel.add(button, gbc);
    }
    
    /**
     * 处理功能按钮点击
     */
    private void handleFunctionButtonClick(ActionEvent e) {
        String command = e.getActionCommand();
        
        // 检查窗口是否已打开
        if (openWindows.containsKey(command) && openWindows.get(command).isVisible()) {
            openWindows.get(command).toFront();
            openWindows.get(command).requestFocus();
            return;
        }
        
        // 创建新窗口
        JFrame newWindow = createFunctionWindow(command);
        if (newWindow != null) {
            openWindows.put(command, newWindow);
            newWindow.setVisible(true);
        }
    }
    
    /**
     * 创建功能窗口
     */
    private JFrame createFunctionWindow(String command) {
        JFrame frame = null;
        
        switch (command) {
            case "user_info":
                frame = new UserInfoFrame(client, currentUser);
                break;
            case "user_mgmt":
                frame = new UserManagementFrame(client, currentUser);
                break;
            case "library_mgmt":
                frame = new com.seu.vcampus.view.library.LibraryManagementFrame(client, currentUser);
                break;
            case "library":
                frame = new com.seu.vcampus.view.library.LibraryFrame(client, currentUser);
                break;
            case "course_select":
            case "course_mgmt":
                frame = new CourseFrame(client, currentUser);
                break;
            case "student_mgmt":
                frame = new StudentFrame(client, currentUser);
                break;
            case "store":
                frame = new StoreFrame(client, currentUser);
                break;
            case "finance_mgmt":
                frame = new FinanceFrame(client, currentUser);
                break;
            case "system_mgmt":
                frame = new SystemFrame(client, currentUser);
                break;
            default:
                JOptionPane.showMessageDialog(this, 
                    "功能正在开发中...", "提示", JOptionPane.INFORMATION_MESSAGE);
                return null;
        }
        
        return frame;
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                closeAllWindows();
                logout();
            }
        });
    }
    
    /**
     * 关闭所有打开的窗口
     */
    private void closeAllWindows() {
        for (JFrame window : openWindows.values()) {
            if (window != null && window.isVisible()) {
                window.dispose();
            }
        }
        openWindows.clear();
    }
    

    
    /**
     * 退出登录
     */
    private void logout() {
        int confirm = UIStyleUtil.showModernConfirmDialog(this, 
            "确定要退出登录吗？", "退出确认");
        
        if (confirm == JOptionPane.YES_OPTION) {
            closeAllWindows();
            
            // 清理客户端状态
            try {
                client.disconnect();
            } catch (Exception e) {
                // 忽略清理过程中的异常
            }
            
            dispose();
            
            // 返回登录界面
            SwingUtilities.invokeLater(() -> {
                VCampusClient newClient = new VCampusClient("localhost", 8888);
                if (newClient.connect()) {
                    ModernLoginFrame loginFrame = new ModernLoginFrame(newClient);
                    loginFrame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, 
                        "无法连接到服务器", "连接失败", JOptionPane.ERROR_MESSAGE);
                }
            });
        }
    }
}